import { GameMode, Player, world } from "@minecraft/server";
import { GameComponent } from "@sapi-game/main";
import { EffectIds, EntityTypeIds } from "@sapi-game/utils/vanila-data";
import { ElevatorCatPlayer } from "@/elevatorCat/player";
import { eleCatchState } from "../state";

export class ElevatorCatchComponent extends GameComponent<eleCatchState> {
    override onAttach(): void {
        this.subscribe(world.afterEvents.entityHitEntity, (t) => {
            if (
                t.damagingEntity.typeId != EntityTypeIds.Player ||
                t.hitEntity.typeId != EntityTypeIds.Player
            ) {
                return;
            }
            const cat = this.context.cat.getById(t.damagingEntity.id);
            const mouse = this.context.mouse.getById(t.hitEntity.id);
            if (cat && mouse) {
                this.handleCatch(cat, mouse);
            }
        });
    }

    handleCatch(cat: ElevatorCatPlayer, mouse: ElevatorCatPlayer) {
        if (!mouse.player || !cat.player) return;
        if (cat.attckCooldown > 0) {
            cat.runCommand("title @s title §8请等待冷却结束");
            return;
        }
        //放羊后不能抓
        if (this.state.isSheep) return;

        cat.attckCooldown = this.context.config.attackCooldown;
        mouse.lives--;
        mouse.player.addEffect(EffectIds.Speed, 40);
        if (mouse.lives <= 0) {
            this.onDie(mouse.player);
        } else {
            mouse.actionbar(`剩余 §c${mouse.lives}§r 条命`);
        }
        cat.player.addEffect(
            EffectIds.Slowness,
            this.context.config.attackCooldown * 20,
            {
                amplifier: 10,
                showParticles: false,
            }
        );
    }

    /**死的时候执行 */
    onDie(player: Player) {
        player.runCommand("title @s subtitle 菜，就多练");
        player.runCommand("title @s title §c寄");
        player.setGameMode(GameMode.Spectator);
        this.context.group.sendMessage(`§e${player.name} 被捕了`);
        this.context.group.forEach((p) => p.player?.playSound("mob.cat.hit"));
    }
}
